
var Cc = Components.classes;
var Ci = Components.interfaces;

function MementoUIClient() {
	this.timemachine = Cc['@www.mementoweb.org/mementofox;1']
	                      .createInstance(Ci.nsIMementoFox);
	this.timemachine.start();
	
	this.prefs = Cc["@mozilla.org/preferences-service;1"]
                    .getService(Ci.nsIPrefService)
                    .getBranch("extensions.memento.");
	this.prefs.QueryInterface(Ci.nsIPrefBranch2);
}

MementoUIClient.prototype = {

		timemachine : null,
		prefs : null,
		
		getCurrentWindow : function() {
		    // Get current window
		    var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
		                   .getService(Ci.nsIWindowMediator);
		    return wm.getMostRecentWindow("navigator:browser");
		},

		refreshMenubar : function() {
			// prefs have changed on a display element, so refresh
			
			window = this.getCurrentWindow();
			if (window == null) {
				return;
			}
			
			if (this.prefs.getBoolPref('hideToolbarWhenInactive')) {
				mb = window.document.getElementById('mementofox-toolbar');
				mb.hidden = true;
			}
			
			sl = window.document.getElementById('targetDateSlideBox');
			pk = window.document.getElementById('targetDatePicker');
			tb = window.document.getElementById('targetDateTextBox');
			rdl = window.document.getElementById('reqDateLabel');
			
			if (this.prefs.getBoolPref('hideWhenInactive')) {
				sl.hidden = true;
				pk.hidden = true;
				tb.hidden = true;
				rdl.hidden = true;
			} else {
				rdl.hidden = false;
				sl.hidden = !this.prefs.getBoolPref("displaySlider");
				pk.hidden = !this.prefs.getBoolPref("displayPicker");
				tb.hidden = !this.prefs.getBoolPref('displayText');
			}
			
		},

		gotoVersion: function(what) {
			loc = what.getAttribute('tooltiptext');
			if (loc) {
				var win = this.getCurrentWindow();
				if (win) {
					// first split on ' @ '
					arr = loc.split('\n @ ');
					this.timemachine.setDatetime(arr[1]);
				}	
				
			}
		},

		swapToInput: function(what) {
		    var inp = document.getElementById("targetDateInput");
		    inp.value = what.value;
		    inp.size = what.value.length;
		    what.hidden = true;
		    inp.hidden = false;
		    // Focus works fine on mac/linux, but windows leaves input uneditable
		    // however select on linux/mac is annoying...	    
		    var opersys = Components.classes['@mozilla.org/xre/app-info;1']
		                                     .getService(Components.interfaces.nsIXULRuntime).OS
		    if (opersys == "WINNT") {
		      inp.select();
		    } else {
		      inp.focus();
		    }
		},

		swapToLabel: function(what) {
		    var inp = document.getElementById("targetDateLabel");
		    if (!what.value) {
		      // need a label to click on!
		      what.value = '0000-00-00';
		    }
		    inp.value = what.value;
		    inp.size = what.value.length;
		    what.hidden = true;
		    inp.hidden = false;
		},

		actualToTarget: function(actual) {
		    tmp = actual.value;
		    var inp = document.getElementById("targetDateLabel");
		    inp.value = tmp;
		},

		setSlider: function(slide) {
		    this.timemachine.setSlider(slide.value);
		},

		fixSlider: function(slide) {
		    this.timemachine.fixSlider(slide.value);
		},

		setEnabled: function(what) {
		    this.timemachine.toggleState(true);
		},

		showWarning: function(what) {
			warn = this.timemachine.getWarning();
			alert(warn);
		},

		showAbout: function(img) {
			if (!img.dlg || img.dlg.closed) {
				img.dlg = window.openDialog("chrome://mementofox/content/about.xul", "aboutMementoFox", "chrome,titlebar,toolbar,centerscreen,resizable")
			} else {
				img.dlg.close();
			}
		},

		setFromPicker: function(pck) {
			date = pck.dateValue;
			date.setUTCHours(12);
			date.setUTCMinutes(0);
			date.setUTCSeconds(0);
			this.timemachine.setDatetime(date.toUTCString());
		},

		setTargetDate: function(tb) {
		    swapToLabel(tb);
		    dt = tb.value;
		    if (dt == '0000-00-00') {
		    	this.timemachine.setDatetime(null);
		    	return;
		    }
		    var result = dt.match(/(\d+)[-/\.](\d+)[-/\.](\d+)\s+(\d+):(\d+)/);
		    if (!result) {
		        result = dt.match(/(\d+)[-/\.](\d+)[-/\.](\d+)/);
		    }
		    if (result) {
		        var year = result[1];
		        var month = result[2]-1;    // Month numbered from 0 !
		        var day = result[3];
		        if (year < 80) {
		            year = 2000 + 1*year;
		        }
		        else if (year < 100) {
		            year = 1900 + 1*year;
		        }
		        var hour = 12;
		        var minute = 0;
		        if (result.length == 6) {
		            hour = result[4];
		            minute = result[5];
		        }
		        var date = new Date(year, month, day, hour, minute, 0);
		        this.timemachine.setDatetime(date.toUTCString());   
		    } else {
		        this.timemachine.setDatetime(null);        
		    }
		}
}


memUiClient = new MementoUIClient();
window.addEventListener('load', memUi_refreshMenubar, false);

// wrapper functions for events

function memUi_refreshMenubar() {
	memUiClient.refreshMenubar();
}

function memUi_handleEvent(elm, arg) {
	return memUiClient[arg](elm);
}
